package com.dnjn.happiness.common.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.dnjn.happiness.common.security.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author: amber
 */
@Slf4j
@Order(1000)
@Component
public class CustomTenantLineHandler implements TenantLineHandler {


    public static final String DEFAULT_TENANT_ID = "0";


    private final TenantProps properties;

    public CustomTenantLineHandler(TenantProps properties) {
        this.properties = properties;
    }

    @PostConstruct
    public void init() {
        log.info("==== init ");
    }

    /**
     * 获取租户ID 实际应该从用户信息中获取
     *
     * @return
     */
    @Override
    public Expression getTenantId() {
        try {
            String tenantId = TokenService.getTenantId();

            log.info("tenantId: {}", tenantId);
            return new StringValue(tenantId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new StringValue(DEFAULT_TENANT_ID);

    }

    @Override
    public String getTenantIdColumn() {
//        properties.getColumn();
        return "tenant_id";
    }

    /**
     * 表过滤，返回true，表示当前表不进行租户过滤
     *
     * @param tableName 表名
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        log.info("can I ignore Table {} ?", tableName);
        /*String loginName=SecurityUtils.getTenantUsername();
        if(null!=ignoreLoginNames && ignoreLoginNames.contains(loginName)){
            return true;
        }*/
       /* String tenantId = getTokenService().getTenantId();
        if (StringUtils.isBlank(tenantId)) {
            return true;
        }*/
        if (Objects.nonNull(TenantContext.get())) {
            log.info("是否做租户隔离:{}", TenantContext.get());
            return TenantContext.get();
        }

        if(tableName.toLowerCase().startsWith("qrtz")){
            return true;
        }
        try {
            return properties.getIgnoreTable().stream().anyMatch(e -> e.equalsIgnoreCase(tableName));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;

    }


}
